<?php if ( ! defined("BASEPATH")) exit("No direct script access allowed!");

/*!
 * Oemah Code CONTROLLER
 * 
 * @package Oemah Code BACKBONE (APPLICATION CORE)
 * @COPYRIGHT OEMAHCODE
 * @author Ones Lynxs
 * @version 1.0
 * @access PUBLIC
 */
class OC_Controller extends CI_Controller {
	
	var $cache_max_time = 2592000; // 30 days
	var $session_check  = FALSE;
	var $login_check    = FALSE;
	var $access_check   = FALSE;

	public function _remap($method, $args)
	{
		if (substr($method, 0, 6) == 'thumb_')
		{
			$prop  = explode('_', $method);
			$size  = explode('x', $prop[1]);
			$image = '/'.implode('/', $args);
			
			return call_user_func_array(
				array($this, '_create_thumb'),
				array(
					$image,
					$size[0],
					$size[1]
				)
			);
		}
	}

	public function __construct($config = array())
	{
		parent::__construct();

		if (count($config) > 0)
		{
			foreach($config as $k => $v)
			{
				$this->$k = $v;
			}
		}

		$this->load->library('bitauth');

		if ($this->login_check == TRUE) $this->validate_login();
		if ($this->access_check == TRUE) $this->validate_access();

		$this->load->config(OC_THEME_CONFIG);
		$this->load->library('theme');
		
		$mod = $this->router->fetch_module();
		$ctl = $this->router->fetch_class();
		
		preg_match("/(" . $mod . "|" . $mod . "\/" . $ctl . ")\/(mod|app|pub|theme)(image|style|script|font)\/(.*)/", $this->uri->uri_string(), $matches);
		if (count($matches) > 0)
		{
			$this->_asset_proxy($matches[3], $matches[4], $matches[2], $mod);

			exit();
		}

		$this->_get_footer();
	}

	public function view($body, $layout = 'main')
	{
		if (OC_MODULE_DIR == 'module_front')
		{
			/*$datamenu				= $this->_get_menu();
			$this->header['menu']	= $this->build_tree_menu($datamenu, 0);*/
			// print_r($this->header['menu']);exit;
		}

		$this->theme->set_layout($layout);
		
		if (ENVIRONMENT == 'production') echo html_uglify($this->theme->view($body, $this->header, TRUE));
		else $this->theme->view($body, $this->header);
	}

	/*private function _get_menu()
	{
		$this->load->model('menu/menu_model', 'get_menu');

		return $this->get_menu->get_menu()->result_array();
	}

	function build_tree_menu($menus, $parent = 0)
	{
		$html = "";

		if (count($menus) > 0)
		{
			foreach($menus as $row)
			{
				if ($row['parent_id'] == $parent)
				{
					
					$has_child 	= $this->menu_has_child($menus, $row['id']);
					$mod   		= $row['name'];

					if ($has_child || $row['parent_id'] != 0)
					{
						if($row['link'] == '#') $url = '#';
						else $url   = site_url($row['link']);
						
						$html .= "<li class='dropdown'>";
						$html .= "<a href='".$url."' class='dropdown-toggle' data-toggle='dropdown'>".$row['name']."</a>";
						$html .= "\n";
						$html .= "<ul class='dropdown-menu'>\n";
						$html .= $this->build_tree_menu($menus, $row['id']);
						$html .= "</ul>\n";
						$html .= "</li>\n";
					}
					else if ($row['parent_id'] == 0)
					{
						if($row['link'] == '') $url = site_url();
						else $url   = site_url($row['link']);

						$html .= "<li>";
						$html .= "<a href='".$url."'>".$row['name']."</a>";
						$html .= "\n";
						$html .= "</li>\n";
					}
				}
			}
		}
		return $html;
	}

	function menu_has_child($menus, $id)
	{
		if (count($menus) > 0)
		{
			foreach($menus as $row)
			{
				if ($row['parent_id'] == $id) return TRUE;
			}
		}

		return FALSE;
	}*/

	private function _asset_proxy($type, $asset, $scope, $mod)
	{
		$file = NULL;
		switch ($scope)
		{
			case 'mod': 
				switch ($type)
				{
					case 'image': $file = OC_APP_DIR.APPPATH.'module_front/'.$mod.'/ocimages/'.$asset; break;
					case 'script': $file = OC_APP_DIR.APPPATH.'module_front/'.$mod.'/ocscripts/'.$asset; break;
					case 'style': $file = OC_APP_DIR.APPPATH.'module_front/'.$mod.'/ocstyles/'.$asset; break;
				}
			break;
			case 'app': 
				switch ($type)
				{
					case 'image': $file = OC_FRONT_DIR.'ocimages/'.$asset; break;
					case 'script': $file = OC_FRONT_DIR.'ocscripts/'.$asset; break;
					case 'style': $file = OC_FRONT_DIR.'ocstyles/'.$asset; break;
				}
			break;
			case 'pub': 
				switch ($type)
				{
					case 'image':
					case 'script':
					case 'style': $file = OC_NEEDS_DIR.$asset; break;
				}
			break;
			case 'theme':
				$theme = config_item('theme');
				switch ($type)
				{
					case 'image': $file = $theme['path'].$theme['theme'].'/img/'.$asset; break;
					case 'script': $file = $theme['path'].$theme['theme'].'/js/'.$asset; break;
					case 'style': $file = $theme['path'].$theme['theme'].'/css/'.$asset; break;
					case 'font': $file = $theme['path'].$theme['theme'].'/fonts/'.$asset; break;
				}
			break;
		}

		if (ENVIRONMENT == 'production') $file = str_replace(array('.js', '.css'), array('-min.js', '-min.css'), $file);
		if ( ! empty($file) && file_exists($file) && ! is_dir($file))
		{
			$mime = get_mime_by_extension($file);

			if ( ! $mime) 
			{
				if (preg_match("/\.(woff|eot|ttf|otf)$/", $file, $matches))
				{
					$ext = $matches[1];
					switch ($ext)
					{
						case 'woff': $mime = 'application/x-font-woff'; break;
						case 'eot': $mime = 'application/vnd.ms-fontobject'; break;
						case 'ttf': $mime = 'font/ttf'; break;
						case 'otf': $mime = 'font/otf'; break;
						default: $mime = 'application/octet-stream';
					}
				}
				else $mime = 'application/octet-stream';
			}

			if (filesize($file) == 0) exit();

			$lastmod	= filemtime($file);
			$etag		= md5_file($file);

			header('Content-Type: '.$mime);
			header('Content-Length: '.filesize($file));
			header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastmod)." GMT");
			header("Etag: ".$etag);

			/*if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $lastmod || @trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag)
			{
				header("HTTP/1.1 304 Not Modified");
				exit();
			}*/
			
			if ($type == 'style' || $type == 'script')
			{
				$s = array('$appimage', '$appstyle', '$appstyle', '../fonts');
				$r = array(
					site_url($this->uri->segment(1).'/appimage'),
					site_url($this->uri->segment(1).'/appstyle'),
					site_url($this->uri->segment(1).'/appscript'),
					site_url($this->uri->segment(1).'/themefont')
				);

				$tmp = file_get_contents($file);
				$tmp = str_replace($s, $r, $tmp);

				print($tmp);
			}
			else 
			{
				print(file_get_contents($file));
			}

		}
		else show_404();
	}

	function serve_file_resumable ($file, $contenttype = 'application/octet-stream', $output = 'display') {

		@error_reporting(0);

		if ( ! file_exists($file)) {
			header("HTTP/1.1 404 Not Found");
			exit;
		}

		if (isset($_SERVER['HTTP_RANGE'])) 
			$range = $_SERVER['HTTP_RANGE'];
		else if ($apache = apache_request_headers()) 
		{ 
			$headers = array();
			
			foreach ($apache as $header => $val) 
				$headers[strtolower($header)] = $val;

			if (isset($headers['range'])) 
				$range = $headers['range'];
			else 
				$range = FALSE;
		} 
		else 
			$range = FALSE;

		$filesize = filesize($file);
		
		if ($range) {
			$partial = true;

			list($param,$range) = explode('=',$range);

			if (strtolower(trim($param)) != 'bytes') 
			{ 
				header("HTTP/1.1 400 Invalid Request");
				exit;
			}

			$range = explode(',',$range);
			$range = explode('-',$range[0]);

			if (count($range) != 2) 
			{
				header("HTTP/1.1 400 Invalid Request");
				exit;
			}

			if ($range[0] === '') 
			{
				$end = $filesize - 1;
				$start = $end - intval($range[0]);
			} 
			else if ($range[1] === '') 
			{
				$start = intval($range[0]);
				$end = $filesize - 1;
			} 
			else 
			{
				$start = intval($range[0]);
				$end = intval($range[1]);
				if ($end >= $filesize || (!$start && (!$end || $end == ($filesize - 1)))) 
					$partial = false;
			}      
			
			$length = $end - $start + 1;

		} else 
			$partial = false;

		header("Content-Type: $contenttype");
		header("Content-Length: $filesize");

		if ($output == 'download')
			header('Content-Disposition: attachment; filename="'.basename($file).'"');

		header('Accept-Ranges: bytes');

		if ($partial) 
		{
			header('HTTP/1.1 206 Partial Content'); 
			header("Content-Range: bytes $start-$end/$filesize"); 
			
			if (!$fp = fopen($file, 'r')) 
			{
				header("HTTP/1.1 500 Internal Server Error");
				exit;
			}

			if ($start) fseek($fp,$start);

			while ($length) 
			{
				$read = ($length > 8192) ? 8192 : $length;
				$length -= $read;
				print(fread($fp,$read));
			}
			fclose($fp);
		} 
		else 
			readfile($file);

		exit;

	}

	private function _get_footer()
	{
		$this->header['wah_footer'] = '<div class=\'wah\'><span>CMS</span> is one of the companies in Indonesia which is engaged in the manufacture of software services, procurement of computer hardware and training of IT technology development</div>';
	}

	function validate_login()
	{
		if( ! $this->bitauth->logged_in())
		{
			$this->session->set_userdata('redir', current_url());
			redirect('auth/login');
			exit;
		}
	}

	function validate_access()
	{

	}

	private function _create_thumb($image, $width = 100, $height = 100, $ratio = NULL)
    {
    	
        $this->load->library('thumb');

		if (empty($ratio)) $ratio = "$width:$height";

		$ds 	= DIRECTORY_SEPARATOR;
		$path 	= NULL;

		preg_match('/\/(pub|app|theme)image(.*)/', $image, $matches);
		
		if (count($matches) > 0)
		{
			switch($matches[1])
			{
				case 'pub': $path  = OC_NEEDS_DIR.'ocimages'.$ds; break;
				case 'app': $path  = OC_FRONT_DIR.'ocimages'.$ds; break;
				case 'theme': 
					$theme = config_item('theme');
					$path  = $theme['path'].$theme['theme'].$ds.'img'.$ds;
					$path  = str_replace(array('/', '\\'), array($ds, $ds), $path);
				break;
			}

			$image = explode('/', $image);

			$this->thumb->initialize(array(
	            'image'  => $path.$matches[2],
	            'width'  => $width,
	            'height' => $height,
	            'ratio'  => $ratio
	        ));

	        $this->thumb->render();

		} else show_404();
    }

    public function print_out($param)
    {
    	echo '<pre>';
    	print_r($param);
    	echo '</pre>';
    	exit;
    }
}